package com.shop.common;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.regex.Pattern;

import com.bill99.seashell.common.util.StringUtil;
import com.bill99.seashell.exception.util.logging.Bill99Logger;

public class MoneyUtil {
	private static  Bill99Logger log = Bill99Logger.getLogger(MoneyUtil.class);
	/**
	 * 将厘转换成分,小数点保留两位,且四舍五入.
	 * 
	 * @param amount
	 *            精确到厘的金额.
	 * @return BigDecimal.
	 */
	public static BigDecimal formatMoney(BigDecimal amount) {
		return amount.divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
	}
	
	
	
	
	/**
	 * 
	 * @param dec
	 * @param srcAmont
	 * @param rateAmont
	 * @return
	 */
public static BigDecimal getRatemoney(BigDecimal dec,BigDecimal srcAmont,BigDecimal rateAmont){
	log.info("dec>>>>>"+dec);
	BigDecimal tempAmont=srcAmont.divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);
	log.info("tempAmont>>>>>"+tempAmont);
	BigDecimal cfaRate=rateAmont.divide(new BigDecimal(100000), 5, RoundingMode.HALF_UP);
	log.info("cfaRate>>>>>"+cfaRate);
	BigDecimal dataAmont=tempAmont.multiply(cfaRate).setScale(3,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP);
	log.info("dataAmont>>>>>"+dataAmont);
	return dec.add(dataAmont);
}
	/**
	 * 将厘转换成分,小数点保留两位,且四舍五入.
	 * 
	 * @param amount
	 *            精确到厘的金额.
	 * @return String
	 */
	public static String formatMoney2Str(BigDecimal amount) {
		return amount.divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP)
				.toString();

	}

	public static String formatRMBStr(BigDecimal amount) {
		NumberFormat numFormat = NumberFormat.getCurrencyInstance();
		return numFormat.format(amount.divide(new BigDecimal(1000), 2,
				RoundingMode.HALF_UP));
	}

	/**
	 * 判断输入字符串是否为正确金额格式
	 * 
	 * @param moneySrc
	 *            输入字符串
	 * @return true 是正确的金额格式，false 错误的金额格式
	 */

	public static boolean isMoneyNumber(String moneySrc) {
		if (StringUtil.isEmpty(moneySrc)) {
			return false;
		}
		
		int temp = moneySrc.indexOf(".");
		int points2 = moneySrc.lastIndexOf(".");
		if (points2 != temp && temp != 0) {
			return false;
		}
		if (temp == moneySrc.length() - 1) {
			return false;
		}

		String money = moneySrc.replace(".", "");
		if (!isNumeric(money)) {
			return isNumeric(money);
		}
		if (-1 == temp) {
			return true;
		}

		int len = moneySrc.substring(temp).length();
		// System.out.println(temp);
		// int len = temp==null?0:temp.length();
		//		
		if (len > 3 || len == 1) {
			return false;
		}
		if(Double.valueOf(moneySrc)<0){
			return false;
		}
		return true;

	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	
}
